import React from 'react'
import { useNavigate } from 'react-router-dom'
import MenuConfig from '../../config/index'
import * as Icon from '@ant-design/icons'
import { Layout, Menu } from 'antd'
import { useDispatch } from 'react-redux'
import { selectMenuList } from '../../store/reducers/tab'

const { Sider } = Layout

//动态获取icon
console.log(MenuConfig)
function buildMenuTree(items) {
  return items.map(item => {
    const child = {
      key: item.path,
      icon: React.createElement(Icon[item.icon]),
      label: item.label,
    }

    // 如果当前项有子菜单，则递归调用自身处理子菜单
    if (item.children) {
      child.children = buildMenuTree(item.children)
    }

    return child
  })
}

//处理菜单数据
const items = buildMenuTree(MenuConfig)

const CommonAside = ({ isCollapse }) => {
  const navigator = useNavigate()
  const dispatch = useDispatch()
  //添加数据到store
  const setTabsList = val => {
    dispatch(selectMenuList(val))
  }

  //点击菜单
  const selectMenu = e => {
    console.log(e)
    let data
    MenuConfig.forEach(item => {
      if (item.path === e.keyPath[e.keyPath.length - 1]) {
        data = item
        if (e.keyPath.length > 1) {
          data = item.children.find(child => {
            return child.path === e.key
          })
        }
      }
    })
    setTabsList({
      path: data.path,
      name: data.name,
      label: data.label,
    })
    navigator(e.key)
  }

  console.log(isCollapse, 'CommonAside')
  return (
    <Sider trigger={null} collapsed={isCollapse} collapsible>
      <h3 className="app-name">{isCollapse ? '后台' : 'React后台管理系统'}</h3>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={['1']}
        style={{
          height: '100%',
        }}
        items={items}
        onClick={selectMenu}
      />
    </Sider>
  )
}

export default CommonAside
